# -*- encoding: utf-8 -*-
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.decorators import user_passes_test

from django.views.decorators.cache import cache_page

from models import Gallery

@cache_page(60 * 15)
def galleries(request):    
    galleries = request.section.galleries.order_by('order')

    if len(galleries) == 1:
        request.object_id = galleries[0].id
        return gallery(request)
    else:
        return render_to_response('gallery/galleries.html',
                                  {'galleries': galleries,},
                                  context_instance=RequestContext(request))

@cache_page(60 * 15)
def gallery(request):
    gallery = get_object_or_404(Gallery, pk=request.object_id)

    return render_to_response('gallery/gallery.html',
                              {'gallery': gallery,},
                              context_instance=RequestContext(request))

@user_passes_test(lambda u: u.is_superuser)
def changeGalleryOrder(request):
    galleries = Gallery.objects.order_by('order')

    i = 1
    for s in galleries:
        s.order = i
        s.save()
        i += 1

    if request.method == "POST":
        if request.POST['galleries'] == 'order':
            for s in galleries:
                if s.order != request.POST[str(s.order)]:
                    s.order = request.POST[str(s.order)]
                    s.save()

            return HttpResponseRedirect(request.path)
  
    return render_to_response('admin/changeGallerieOrder.html', {'galleries': galleries},
                              context_instance=RequestContext(request))
